#include <iostream>
#include <string>
#include <cstdio>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
using namespace std;

void Usage(string str)
{
    cout << "\n\tUsage: " << str << " serverip serverport\n"
         << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t serverport = stoi(argv[1]); // 字符串转整形
    string serverip = argv[2];

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    // 传入服务器的ip和端口号 使客户端消息向服务器发送
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);
    socklen_t len = sizeof(server);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "socket create error" << endl;
        return 1;
    }

    string message;
    char buffer[1024];
    while (true)
    {
        // 发送数据
        cout << "Please Enter@ ";
        getline(cin, message);

        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, len);

        // 接收数据
        sockaddr_in temp;
        socklen_t len1 = sizeof(temp);

        ssize_t s = recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr *)&temp, &len1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << buffer << endl;
        }
    }

    close(sockfd);

    return 0;
}
